package com.example.lottery.common.handler;

import com.example.lottery.common.errorcode.GlobalErrorCodeConstants;
import com.example.lottery.common.exception.ControllerException;
import com.example.lottery.common.exception.ServiceException;
import com.example.lottery.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.security.Provider;

@Slf4j
@RestControllerAdvice//捕获所有的异常
public class GlobalException {
    //对controller层异常进行处理
    @ExceptionHandler(value=ControllerException.class)
    public CommonResult controllerException(ControllerException e){
        //打印日志
        log.info("ControllerException：{}",e.getMsg());
        e.printStackTrace();//打印异常栈
        //构造结果并返回
        return CommonResult.error(e.getCode(),e.getMsg());
    }

    //对service异常进行处理
    @ExceptionHandler(value= ServiceException.class)
    public CommonResult serviceException(ServiceException e){
        //打印日志
        log.info("ServiceException：{}",e.getMsg());
        e.printStackTrace();//打印异常栈
        //构造结果并返回
        return CommonResult.error(e.getCode(),e.getMsg());
    }

    //兜底
    @ExceptionHandler(value=Exception.class)
    public CommonResult Exception(Exception e){
        //打印日志
        log.info("Exception：{}",GlobalErrorCodeConstants.INTERNAL_SERVICE_ERROR.getMsg());
        e.printStackTrace();//打印异常栈
        //构造结果并返回
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVICE_ERROR);
    }
}
